from Modules.mod_psql import PSQLDB


class Export:

    PATH_EXPORT = r'Task_1_3_and_1_4/export_files/'

    def __init__(self, name_schema: str):
        self.name_schema = name_schema

    def from_tables(self, name_table: str):
        connection = PSQLDB().connection()
        cursor = connection.cursor()
        query: str = f"""COPY (SELECT row_number() OVER() as row, * FROM {self.name_schema}.{name_table}) TO STDOUT With CSV HEADER DELIMITER ';'"""
        with open(f"{self.PATH_EXPORT}{name_table}.csv", "w", encoding='utf-8') as file:
            cursor.copy_expert(query, file)
        PSQLDB().exit_db(connection)

    def from_function(self, name_function: str, input: str):
        connection = PSQLDB().connection()
        cursor = connection.cursor()
        query: str = f"""COPY (SELECT row_number() OVER() as row, * FROM {self.name_schema}.{name_function} ('{input}')) TO STDOUT With CSV HEADER DELIMITER ';'"""
        with open(f"{self.PATH_EXPORT}{name_function}.csv", "w", encoding='utf-8') as file:
            cursor.copy_expert(query, file)
        PSQLDB().exit_db(connection)
